package com.yxsk.relay.job.admin.config.registry.security;

import com.yxsk.relay.job.admin.data.entity.JobApps;
import com.yxsk.relay.job.admin.data.service.JobAppsService;
import com.yxsk.relay.job.component.admin.exception.registry.RelayJobRegistryException;
import com.yxsk.relay.job.component.admin.registry.security.SecurityChecker;
import com.yxsk.relay.job.component.common.vo.SlaveInfo;
import lombok.AllArgsConstructor;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @Author 11376
 * @CreaTime 2019/7/1 21:04
 * @Description token 安全检查
 */
@AllArgsConstructor
public class TokenSecurityChecker implements SecurityChecker {

    private List<String> authToken;

    private JobAppsService appsService;

    @Override
    public void check(SlaveInfo slaveInfo, String token) throws RelayJobRegistryException {
        if (CollectionUtils.isEmpty(authToken) || !StringUtils.hasLength(token)) {
            // 不存在授权 token
            throw new RelayJobRegistryException("token error.");
        }

        // 授权token中不存在此 token
        if (!authToken.contains(token)) {
            throw new RelayJobRegistryException("Untrusted token.");
        }
    }

    @Override
    public boolean isCheck(SlaveInfo slaveInfo, String token) {
        JobApps apps = this.appsService.findByAppName(slaveInfo.getAppName());
        return apps == null || JobApps.AuthType.TOKEN.getType().equals(apps.getAuthType());
    }

    public void updateAuthToken(List<String> authToken) {
        List<String> tokens = new ArrayList<>();
        Collections.copy(authToken, tokens);
        this.authToken = tokens;
    }

    public List<String> getAuthToken() {
        if (CollectionUtils.isEmpty(authToken)) {
            return Collections.emptyList();
        }
        List<String> tokens = new ArrayList<>();
        Collections.copy(authToken, tokens);
        return tokens;
    }

}
